package com.cupdata.marathon.common;

import cn.hutool.core.util.StrUtil;
import com.cupdata.marathon.bean.Result;
import com.cupdata.marathon.bean.User;
import com.cupdata.marathon.client.UserCheckService;
import com.cupdata.marathon.definition.OperUserRslt;
import com.cupdata.marathon.definition.RspCd;
import com.cupdata.marathon.param.usercheck.UserCheckRequest;
import com.cupdata.marathon.param.usercheck.UserCheckResponse;
import com.cupdata.marathon.utils.GsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 验证用户信息
 */
@Service
public class UserInfoCheckService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserCheckService userCheckService;



    public Result userInfoCheck(String userId, String traceId) {
        String userInfo = stringRedisTemplate.opsForValue().get(userId);
        if (StrUtil.isBlank(userInfo)) {
            // 缓存中没有用户数据，发起http请求获取
            UserCheckRequest checkRequest = new UserCheckRequest();
            checkRequest.setUserId(userId);
            checkRequest.setTransId(traceId);

            UserCheckResponse userCheckResponse = userCheckService.call(checkRequest);
            // 请求返回调用失败
            if (RspCd.FAIL.getCode().equals(userCheckResponse.getRspCd())) {
                return new Result(RspCd.FAIL.getMsg(), RspCd.FAIL.getCode());
            }

            User user = new User();
            if (OperUserRslt.O0000.getCode().equals(userCheckResponse.getOperRslt())) {
                // 用户验证通过
                user.setOneCount(0);
                user.setTwoCount(0);
                user.setCouponWorth(0);
                user.setStatus(OperUserRslt.O0000.getCode());
                stringRedisTemplate.opsForValue().set(userId, GsonUtils.gson.toJson(user));
            } else {
                //检查失败 返回错误码
                user.setStatus(userCheckResponse.getOperRslt());
                stringRedisTemplate.opsForValue().set(userId, GsonUtils.gson.toJson(user));
                return new Result(userCheckResponse.getRspMsg(), userCheckResponse.getRspCd());
            }
        } else {
            User user = GsonUtils.gson.fromJson(userInfo, User.class);
            if (!"0000".equals(user.getStatus())) {
                return new Result(OperUserRslt.valueOf("O" + user.getStatus()).getMsg(), user.getStatus());
            }
        }

        return null;
    }
}
